package com.wondertek.mam.tag.wordSource;

import com.wondertek.mam.tag.domain.TagDB;
import com.wondertek.mam.tag.repository.TagRepository;
import com.wondertek.mam.tag.wordSource.bean.NetHotWord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 保存热词
 * Created by wangdongxu on 2017-09-12 下午 15:44:22.
 */
public class SaveNetHotWordDB implements SaveNetHotWord {
    private static final Logger LOGGER = LoggerFactory.getLogger(SaveNetHotWordDB.class);
    private TagRepository tagRepository;

    public SaveNetHotWordDB(TagRepository tagRepository) {
        this.tagRepository = tagRepository;
    }

    @Override
    public void save(NetHotWord netHotWord) {
        if (netHotWord ==null) {
            return;
        }
        LOGGER.debug("词语入库"+netHotWord.getWords().keySet());
        //更新已存在的内容
        List<TagDB> allByTagInAndTop = tagRepository.findAllByTagInAndTop(netHotWord.getWords().keySet(), netHotWord.getKeyWord())
            .parallelStream()
            .map(tagDB -> {
                if (netHotWord.getWords().get(tagDB.getTag())==null)return tagDB;
                tagDB.setCreateTime(LocalDateTime.now());
                tagDB.setScore(netHotWord.getWords().get(tagDB.getTag())?5:4);
                tagDB.setHot(netHotWord.getWords().get(tagDB.getTag()));
                return tagDB;
            })
            .collect(Collectors.toList());
        tagRepository.save(allByTagInAndTop);
        //增加新内容
        List<String> tagWords = allByTagInAndTop
            .parallelStream()
            .map(TagDB::getTag)
            .collect(Collectors.toList());
        List<TagDB> collect = netHotWord.getWords().entrySet()
            .parallelStream()
            .filter(stringBooleanEntry -> !tagWords.contains(stringBooleanEntry.getKey()))
            .map(stringBooleanEntry -> new TagDB(
                stringBooleanEntry.getKey(),
                netHotWord.getKeyWord(),
                LocalDateTime.now(),
                stringBooleanEntry.getValue()?5:4
                ,stringBooleanEntry.getValue())
            )
            .collect(Collectors.toList());
        tagRepository.save(collect);
    }
}
